package com.ruoyi.common.filter;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.slf4j.spi.MDCAdapter;

import java.io.IOException;
import java.net.InetAddress;

/**
 * @title 为logback日志增加traceId
 */
@WebFilter(urlPatterns = "/*", filterName = "logMdcFilter")
public class LogMdcFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        insertMDC((HttpServletRequest) request);
        try {
            chain.doFilter(request, response);
        } finally {
            MDCAdapter mdc = MDC.getMDCAdapter();
            mdc.clear();
        }
    }

    @Override
    public void destroy() {
    }

    private boolean insertMDC(HttpServletRequest request) {
        String traceId = request.getParameter("traceId");
        String uniqueId = StrUtil.isEmpty(traceId) ? IdUtil.simpleUUID() : traceId;
        MDCAdapter mdc = MDC.getMDCAdapter();
        mdc.put("uri", request.getRequestURI());
        //mdc.put("ip", ServletUtil.getClientIP(request, null));
        mdc.put("traceId", uniqueId);
        InetAddress address = NetUtil.getLocalhost();
        mdc.put("localHost", address != null ? address.getHostAddress() : "");
        return true;
    }
}